package com.example.springboot.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.Result;
import com.example.springboot.controller.dto.HomestaysDTO;
import com.example.springboot.entity.*;
import com.example.springboot.mapper.FacilitiesMapper;
import com.example.springboot.mapper.HomestayFacilitiesMapper;
import com.example.springboot.mapper.HomestayImagesMapper;
import com.example.springboot.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 民宿表 API控制器 - 专门用于不需要token验证的API
 * </p>
 *
 * @author
 */
@RestController
@RequestMapping("/api/homestays")
public class HomestaysApi {

    @Resource
    private IHomestaysService iHomestaysService;




    @Resource
    private IFacilitiesService iFacilitiesService;

    @Resource
    private HomestayFacilitiesMapper homestayFacilitiesMapper;

    @Resource
    private HomestayImagesMapper imagesMapper;




    //民宿列表，分页返回
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String type,
                           @RequestParam Integer page,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String area,
                           @RequestParam(defaultValue = "") String minPrice,
                           @RequestParam(defaultValue = "") String maxPrice,
                           @RequestParam(defaultValue = "") String keyword,
                           @RequestParam(defaultValue = "") String capacity) {
        QueryWrapper<Homestays> queryWrapper = new QueryWrapper<>();
        //筛选条件
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("status",1);
        if (!"".equals(keyword)) {
            if (!"".equals(keyword)) {
                queryWrapper.and(wrapper ->
                        wrapper.like("name", keyword)
                                .or()
                                .like("area", keyword)


                );
            }
        }
        if (!"".equals(type)) {
            queryWrapper.like("type", type);
        }
        if (!"".equals(capacity)) {
            queryWrapper.like("capacity", capacity);
        }

        if (!"".equals(area)) {
            queryWrapper.like("area", area);
        }

        // 处理价格范围筛选
        if (!"".equals(minPrice) && !"".equals(maxPrice)) {
            // 既有最低价又有最高价
            queryWrapper.between("price", minPrice, maxPrice);
        } else if (!"".equals(minPrice)) {
            // 只有最低价
            queryWrapper.ge("price", minPrice);
        } else if (!"".equals(maxPrice)) {
            // 只有最高价
            queryWrapper.le("price", maxPrice);
        }

        return Result.success(iHomestaysService.page(new Page<>(page, pageSize), queryWrapper));
    }

    @GetMapping("/detail/{id}")
    public Result selectDetails(@PathVariable Integer id) {
        // 1. 查询民宿
        Homestays homestays = iHomestaysService.getById(id);
        if (homestays == null) {
            return Result.success("文章不存在");
        }

        // 2. 转换为 DTO
        HomestaysDTO dto = new HomestaysDTO();
        BeanUtils.copyProperties(homestays, dto);

        // 3. 查询图片列表
        QueryWrapper<HomestayImages> imagesQueryWrapper = new QueryWrapper<>();
        imagesQueryWrapper.eq("homestay_id", id).eq("is_cover", 0);
        List<HomestayImages> homestayImages = imagesMapper.selectList(imagesQueryWrapper);
        dto.setImages(homestayImages);

        // 4. 查询设施信息
        QueryWrapper<HomestayFacilities> homestayFacilitiesQueryWrapper = new QueryWrapper<>();
        homestayFacilitiesQueryWrapper.eq("homestay_id", id);
        List<HomestayFacilities> facilities = homestayFacilitiesMapper.selectList(homestayFacilitiesQueryWrapper);

        // 获取所有设施ID
        List<Integer> facilityIds = facilities.stream()
                .map(HomestayFacilities::getFacilityId) // 假设getFacilityId()是获取设施ID的方法
                .collect(Collectors.toList());

        // 根据设施ID查询设施详情
        if (!facilityIds.isEmpty()) {
            List<Facilities> facilityDetails = iFacilitiesService.listByIds(facilityIds); // 假设有facilitiesService可以批量查询
            dto.setFacilities(facilityDetails); // 假设DTO中有setFacilities方法
        }

        // 5. 返回包含图片和设施信息的 DTO
        return Result.success(dto);
    }
    //相关推荐
    @GetMapping("/related")
    public Result related(@RequestParam String area) {
        QueryWrapper<Homestays> articlesQueryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(area) && !"0".equals(area)) {
            articlesQueryWrapper.eq("area", area);
        }
        List<Homestays> articlesList = iHomestaysService.list(articlesQueryWrapper);

        if (articlesList.isEmpty()) {
            return Result.success(Collections.emptyList()); // 返回空列表
        }

        Collections.shuffle(articlesList); // 打乱顺序
        int endIndex = Math.min(articlesList.size(), 6); // 最多取 6 个
        List<Homestays> randomArticles = articlesList.subList(0, endIndex);

        return Result.success(randomArticles);
    }

    //更新阅读量
    @PostMapping("/view/{id}")
    public Result updateViewCount(@PathVariable Integer id) {
        imagesMapper.updateViewCount(id);
        return Result.success();
    }

}
